package org.flysli.gadget.plugins.transfer.procer;

import org.flysli.gadget.plugins.transfer.annotation.Round;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class RoundProcer implements ConstraintProcer<Round, Double> {
    public Double process(Round annotation, Double source) {
        if (source == null) {
            source = Double.valueOf(annotation.ifnull());
        }
        return round(source, annotation.digit());
    }

    public Double round(Object number, int digit) {
        if (number == null) {
            throw new RuntimeException("为NULL的元素不可以进行四舍五入操作");
        }
        double d = 0.0;
        try {
            d = Float.valueOf(String.valueOf(number));
            BigDecimal bigDecimal = new BigDecimal(d);
            return bigDecimal.setScale(digit, RoundingMode.HALF_UP).doubleValue();
        } catch (NumberFormatException e) {
            return 0.0;
        }
    }
}
